<template>
  <div class="consolidatedOrderInformation">
    <el-card class="box-card margin-bottom-lg">
      <div slot="header" class="clearfix">
        <span class="title-icon">{{
          $t(`endWaybill.${type === 'expressDelivery' ? 'title2' : 'title'}`)
        }}</span>
      </div>
      <el-form
        ref="consolidatedOrderInfo"
        :model="consolidatedOrderInfo"
        :rules="rules"
        label-position="left"
        label-width="120px"
        size="mini"
        class="text-sm"
      >
        <el-row>
          <el-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            class="padding-40"
          >
            <el-form-item v-if="type === 'expressDelivery'" prop="shipAccount">
              <div slot="label">打单账号:</div>

              <el-tooltip
                class="item"
                content="点击输入可快速搜索"
                effect="light"
                placement="top-end"
              >
                <el-select
                  v-model="consolidatedOrderInfo.shipAccount"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(label, value) in publicData.shippingAccountMap"
                    :key="value"
                    :label="label"
                    :value="value"
                  />
                </el-select>
              </el-tooltip>
            </el-form-item>
            <el-form-item prop="countryId">
              <div slot="label">目的国家:</div>

              <el-tooltip
                class="item"
                content="点击输入可快速搜索"
                effect="light"
                placement="top-end"
              >
                <el-select
                  v-model="consolidatedOrderInfo.countryId"
                  filterable
                  placeholder="请选择"
                  @change="changeCountry"
                >
                  <el-option
                    v-for="item in publicData.countryList"
                    :key="item.value"
                    :label="item.label"
                    :value="parseInt(item.value)"
                  />
                </el-select>
              </el-tooltip>
            </el-form-item>
            <el-form-item prop="masterNumber">
              <div slot="label">主单号:</div>

              <el-input v-model="consolidatedOrderInfo.masterNumber" />
            </el-form-item>
            <el-row :gutter="5">
              <el-col :sm="24" :md="24" :lg="12">
                <el-form-item prop="customerActualWeight">
                  <div slot="label">总实重(KG):</div>

                  <el-input
                    v-model.number="consolidatedOrderInfo.customerActualWeight"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="24" :lg="12">
                <el-form-item prop="customerVolume" class="text-right">
                  <div slot="label">体积(CBM):</div>

                  <el-input
                    v-model.number="consolidatedOrderInfo.customerVolume"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="5">
              <el-col :sm="24" :md="24" :lg="12">
                <el-form-item prop="customerTotalPackages">
                  <div slot="label">件数:</div>

                  <el-input
                    v-model.number="consolidatedOrderInfo.customerTotalPackages"
                    type="number"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="24" :lg="12">
                <el-form-item prop="chargeableWeight" class="text-right">
                  <div slot="label">计费重:</div>

                  <el-input
                    v-model.number="consolidatedOrderInfo.chargeableWeight"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item
              v-if="type !== 'customsClearance'"
              prop="purposeWarehouseType"
              label-width="120px"
            >
              <div slot="label">目的仓库类型：</div>
              <el-radio-group
                ref="aaa"
                v-model="consolidatedOrderInfo.purposeWarehouseType"
              >
                <el-radio
                  v-for="(item, value) in publicData.stockTypeEnableMap"
                  :key="value"
                  :label="parseInt(value)"
                >
                  {{ item }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <div
              v-if="
                type !== 'customsClearance' &&
                  consolidatedOrderInfo.purposeWarehouseType === 100
              "
            >
              <el-form-item prop="dispatchAddressCode">
                <div slot="label">详细地址:</div>
                <el-select
                  v-model="consolidatedOrderInfo.dispatchAddressCode"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, value) in fbaCodeZipCodeMap"
                    :key="value"
                    :label="`${item.address} (${item.fbaCode})`"
                    :value="item.fbaCode"
                  />
                </el-select>
              </el-form-item>
            </div>

            <div
              v-if="
                type !== 'customsClearance' &&
                  consolidatedOrderInfo.purposeWarehouseType !== 100
              "
            >
              <el-form-item prop="dispatcher">
                <div slot="label">公司名/个人:</div>

                <div class="flex">
                  <el-input
                    v-model="consolidatedOrderInfo.dispatcher"
                    type="text"
                  />
                  <el-button
                    type="text"
                    class="margin-left"
                    @click="showImportDialog"
                  >
                    <svg-icon name="international" />
                    常用派送地址
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item prop="dispatchLinkMan">
                <div slot="label">联系人:</div>

                <el-input
                  v-model="consolidatedOrderInfo.dispatchLinkMan"
                  type="text"
                />
              </el-form-item>
              <el-form-item prop="dispatchPhone">
                <div slot="label">联系电话:</div>

                <el-input
                  v-model="consolidatedOrderInfo.dispatchPhone"
                  type="text"
                />
              </el-form-item>
              <el-form-item prop="dispatchProvince">
                <div slot="label">州/省:</div>

                <el-input
                  v-model="consolidatedOrderInfo.dispatchProvince"
                  type="text"
                />
              </el-form-item>
              <el-form-item prop="dispatchCity">
                <div slot="label">城市:</div>

                <el-input
                  v-model="consolidatedOrderInfo.dispatchCity"
                  type="text"
                />
              </el-form-item>
              <el-form-item prop="dispatchZipCode">
                <div slot="label">邮编:</div>

                <div class="flex">
                  <el-input
                    v-model="consolidatedOrderInfo.dispatchZipCode"
                    type="text"
                  />
                  <el-button
                    class="margin-left"
                    type="text"
                    icon="el-icon-s-management"
                    @click="saveShippingAddress"
                  >
                    保存为常用派送地址
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item prop="dispatchAddress">
                <div slot="label">详细地址:</div>

                <el-input
                  v-model="consolidatedOrderInfo.dispatchAddress"
                  type="text"
                />
              </el-form-item>
            </div>
          </el-col>
          <el-col
            v-if="type !== 'truckDelivery' && type !== 'expressDelivery'"
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            class="padding-40"
          >
            <el-form-item prop="estimatedDepartureTime">
              <div slot="label">预计离港时间:</div>
              <el-date-picker
                v-model="consolidatedOrderInfo.estimatedDepartureTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item prop="estimatedArrivalTime">
              <div slot="label">预计到港时间:</div>
              <el-date-picker
                v-model="consolidatedOrderInfo.estimatedArrivalTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item prop="shipmentPort">
              <div slot="label">起运港:</div>
              <el-select
                v-model="consolidatedOrderInfo.shipmentPort"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(label, value) in createTpye === 'ToAirFreight'
                    ? publicData.airPortMap
                    : publicData.portMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item prop="destinationPort">
              <div slot="label">目的港:</div>
              <el-select
                v-model="consolidatedOrderInfo.destinationPort"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(label, value) in createTpye === 'ToAirFreight'
                    ? publicData.airPortMap
                    : publicData.portMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="createTpye !== 'ToAirFreight'"
              prop="shipOrAirlineCompany"
            >
              <div slot="label">船公司:</div>
              <el-select
                v-model="consolidatedOrderInfo.shipOrAirlineCompany"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(label, value) in publicData.shipownerMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col
            v-if="
              type === 'customsClearanceAndSend' || type === 'customsClearance'
            "
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            class="padding-lr-40"
          >
            <el-form-item>
              <div slot="label">附件: <span class="text-red">*</span></div>
              <el-button size="small" type="primary" plain @click="toUpload(1)">
                上传箱单发票
              </el-button>
              <div
                v-for="(item, index) in invoiceList"
                :key="index"
                class="flex align-center "
              >
                <el-link :href="item">
                  {{ item.slice(item.lastIndexOf('/') + 1) }}
                </el-link>
                <i
                  class="el-icon-close text-lg pointer margin-left-lg text-red"
                  @click="onDel(1, index)"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="
              type === 'customsClearanceAndSend' || type === 'customsClearance'
            "
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            class="padding-lr-40"
          >
            <el-form-item prop="channel">
              <div slot="label">附件: <span class="text-red">*</span></div>
              <el-button size="small" type="primary" plain @click="toUpload(2)">
                上传提单
              </el-button>
              <div v-for="(item, index) in pickUpOrderList" :key="index">
                <el-link :href="item">
                  {{ item.slice(item.lastIndexOf('/') + 1) }}
                </el-link>
                <i
                  class="el-icon-close text-lg pointer margin-left-lg text-red"
                  @click="onDel(2, index)"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col
            v-if="type !== 'expressDelivery' && type !== 'customsClearance'"
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            class="padding-lr-40"
          >
            <el-form-item prop="channel">
              <div slot="label">附件: <span class="text-red">*</span></div>
              <el-button size="small" type="primary" plain @click="toUpload(3)">
                上传派送指引
              </el-button>
              <div v-for="(item, index) in deliveryGuideList" :key="index">
                <el-link :href="item">
                  {{ item.slice(item.lastIndexOf('/') + 1) }}
                </el-link>
                <i
                  class="el-icon-close text-lg pointer margin-left-lg text-red"
                  @click="onDel(3, index)"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="
              !isAir &&
                (type === 'customsClearanceAndSend' ||
                  type === 'customsClearance')
            "
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            class="padding-lr-40"
          >
            <el-form-item prop="channel">
              <div slot="label">附件: <span class="text-red">*</span></div>
              <el-button size="small" type="primary" plain @click="toUpload(4)">
                上传ISF文件
              </el-button>
              <div v-for="(item, index) in isfList" :key="index">
                <el-link :href="item">
                  {{ item.slice(item.lastIndexOf('/') + 1) }}
                </el-link>
                <i
                  class="el-icon-close text-lg pointer margin-left-lg text-red"
                  @click="onDel(4, index)"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div
        v-if="type === 'customsClearanceAndSend' || type === 'customsClearance'"
        class="padding"
      >
        <el-button size="small" type="primary" plain @click="toUpload(5)">
          上传清关发票并解析数据
        </el-button>
      </div>
    </el-card>

    <invoices-packing
      v-if="invoicesPackingInfo.liquidationInvoices.length > 0"
      :invoices-packing-info="invoicesPackingInfo"
    />

    <Sub
      v-if="type !== 'expressDelivery'"
      ref="sub"
      :country-id="consolidatedOrderInfo.countryId"
      :fba-code-zip-code-map="fbaCodeZipCodeMap"
    />
    <CargoInfo v-else :goods-info.sync="goodsInfo" />

    <div class="text-center margin-tb">
      <el-button type="primary" @click="submitForm('channelform')">
        保存
      </el-button>
    </div>

    <ImportPop
      :upload-dialog.sync="uploadDialog"
      :dialog-title="importInfo.title"
      :action-url="importInfo.actionUrl"
      :file-name="importInfo.fileName"
      :static-file-name="importInfo.staticFileName"
      @uploadCb="uploadCb"
    />

    <ImportDialog :select-dispatch.sync="selectDispatch" @dialogCb="dialogCb" />
  </div>
</template>

<script>
import ImportPop from '@/components/ImportPop'
import { clone } from '@/utils/clone'
import { future } from '@/utils/validate'
import { mapGetters } from 'vuex'
import {
  saveWaybillHd,
  saveExpressDispatch,
  initShippingfbaStockBycountry,
  getWaybillHdById
} from '@/api/endpoint'
import { customerdeliveryaddressSave } from '@/api/myProfile'
import Sub from './Sub'
import CargoInfo from './CargoInfo'
import InvoicesPacking from './InvoicesPacking'
import ImportDialog from './ImportDialog'
export default {
  name: 'TabPane',
  components: {
    Sub,
    CargoInfo,
    ImportPop,
    InvoicesPacking,
    ImportDialog
  },
  props: {
    type: {
      type: String,
      default: 'customsClearanceAndSend'
    },
    createTpye: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pickerOptions: future(),
      invoicesPackingInfo: {
        liquidationInvoices: []
      },
      uploadDialog: false,
      actionUrl1: '/seaair/seaairwaybillextremes/uploadAccessorys',
      actionUrl2: '/seaair/seaairwaybillextremes/analysisLiquidationPackingHd', // 解析箱单发票
      importInfo: [
        {
          title: '',
          actionUrl: ''
        }
      ],
      fbaCodeZipCodeMap: {},
      selectDispatch: false,
      invoiceList: [],
      pickUpOrderList: [],
      deliveryGuideList: [],
      isfList: [],
      goodsInfo: [{}],
      timer: null,
      list: null,
      portOptions: {},
      shipownerOptions: {},
      consolidatedOrderInfo: {
        shipAccount: '',
        countryId: '',
        purposeWarehouseType: 100,
        customerActualWeight: '',
        customerTotalPackages: '',
        customerVolume: '',
        masterNumber: '',
        estimatedDepartureTime: '',
        estimatedArrivalTime: '',
        shipmentPort: '',
        destinationPort: '',
        shipOrAirlineCompany: '',
        dispatcher: '',
        dispatchLinkMan: '',
        dispatchPhone: '',
        dispatchProvince: '',
        dispatchZipCode: '',
        dispatchCity: '',
        dispatchAddress: ''
      },

      rules: {
        shipAccount: [
          { required: true, message: '请选择打单账号', trigger: 'change' }
        ],
        shipmentPort: [
          { required: true, message: '请选择起运港', trigger: 'change' }
        ],
        destinationPort: [
          { required: true, message: '请选择目的港', trigger: 'change' }
        ],
        shipOrAirlineCompany: [
          { required: true, message: '请选择船公司', trigger: 'change' }
        ],
        countryId: [
          { required: true, message: '请选择目的国家', trigger: 'change' }
        ],
        dispatchAddressCode: [
          { required: true, message: '请选择详细地址', trigger: 'change' }
        ],
        estimatedDepartureTime: [
          { required: true, message: '请选择预计离港时间', trigger: 'blur' }
        ],
        estimatedArrivalTime: [
          { required: true, message: '请选择预计到港时间', trigger: 'blur' }
        ],
        customerActualWeight: [
          { required: true, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '须为数字,可留3位小数'
          }
        ],
        customerVolume: [
          { required: true, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '须为数字,可留3位小数'
          }
        ],
        chargeableWeight: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '须为数字,可留3位小数'
          }
        ],
        customerTotalPackages: [
          { required: true, message: '请填写件数', trigger: 'blur' }
        ],
        masterNumber: [
          { required: false, message: '请填写主单号', trigger: 'blur' }
        ],
        purposeWarehouseType: [
          { required: true, message: '请选择目的仓库', trigger: 'change' }
        ],
        dispatcher: [
          { required: true, message: '请填写公司名/个人', trigger: 'blur' }
        ],
        dispatchLinkMan: [
          { required: true, message: '请填写联系人', trigger: 'blur' }
        ],
        dispatchPhone: [
          { required: true, message: '请填写联系电话', trigger: 'blur' }
        ],
        dispatchProvince: [
          { required: true, message: '请填写州/省', trigger: 'blur' }
        ],
        dispatchZipCode: [
          { required: true, message: '请填写邮编', trigger: 'blur' }
        ],
        dispatchCity: [
          { required: true, message: '请填写城市', trigger: 'blur' }
        ],
        dispatchAddress: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
      goodsRules: {
        cases: '件数',
        length: '长',
        width: '宽',
        height: '高',
        weight: '重量'
      },
      shippingRules: {
        countryId: '目的国家',
        dispatcher: '公司名/个人',
        dispatchLinkMan: '联系人',
        dispatchPhone: '联系电话',
        dispatchProvince: '州/省',
        dispatchZipCode: '邮编',
        dispatchCity: '城市',
        dispatchAddress: '详细地址'
      },
      btnType: 0
    }
  },
  computed: {
    ...mapGetters(['publicData']),
    isAir() {
      return this.createTpye === 'ToAirFreight'
    }
  },

  mounted() {
    this.init()
  },
  destroyed() {
    console.log('离开')
  },
  methods: {
    async init() {
      if (this.createTpye === 'ToAirFreight') {
        this.portOptions = this.publicData.airPortMap
      } else {
        this.portOptions = this.publicData.portMap
      }
      this.shipownerOptions = this.publicData.shipownerMap

      // 回显数据
      if (this.$route.query.waybillId) {
        const { code, data } = await getWaybillHdById({
          id: this.$route.query.waybillId
        })

        if (code === 200) {
          this.consolidatedOrderInfo = data.waybill
          console.log('waybill :>> ', data.waybill)
          this.changeCountry()
          if (data.waybillHdSubCreates.length > 0) {
            this.$refs.sub.subList = data.waybillHdSubCreates
          }
          // 发票　发件人　供应商
          if (data.liquidationInvoices && data.liquidationInvoices.length > 0) {
            this.invoicesPackingInfo.liquidationInvoices =
              data.liquidationInvoices

            this.invoicesPackingInfo.senderCompany = data.waybill.senderCompany
            this.invoicesPackingInfo.senderLinkMan = data.waybill.senderLinkMan
            this.invoicesPackingInfo.senderPhone = data.waybill.senderPhone
            this.invoicesPackingInfo.senderAdress = data.waybill.senderAdress
            this.invoicesPackingInfo.importerCompanyName =
              data.waybill.importerCompanyName
            this.invoicesPackingInfo.importerLinkMan =
              data.waybill.importerLinkMan
            this.invoicesPackingInfo.importerPhone = data.waybill.importerPhone
            this.invoicesPackingInfo.importerZipCode =
              data.waybill.importerZipCode
            this.invoicesPackingInfo.vat = data.waybill.vat
            this.invoicesPackingInfo.eori = data.waybill.eori
            this.invoicesPackingInfo.importerAddress =
              data.waybill.importerAddress
          }
          // 箱单
          if (data.packingLists && data.packingLists.length > 0) {
            this.invoicesPackingInfo.packingLists = data.packingLists
          }
          // 箱单发票文件
          if (data.packLiquFiles && data.packLiquFiles.length > 0) {
            const arr = []
            for (const i of data.packLiquFiles) {
              arr.push(i.fileUrl)
            }
            this.invoiceList = arr
          }
          // 提单文件
          if (data.ladingFiles && data.ladingFiles.length > 0) {
            const arr = []
            for (const i of data.ladingFiles) {
              arr.push(i.fileUrl)
            }
            this.pickUpOrderList = arr
          }
          // 发货指引文件
          if (data.sendToGuideFiles && data.sendToGuideFiles.length > 0) {
            const arr = []
            for (const i of data.sendToGuideFiles) {
              arr.push(i.fileUrl)
            }
            this.deliveryGuideList = arr
          }
          // ISF文件
          if (data.isFtextFiles && data.isFtextFiles.length > 0) {
            const arr = []
            for (const i of data.isFtextFiles) {
              arr.push(i.fileUrl)
            }
            this.isfList = arr
          }
        } else {
          this.$message.error(data.message || '系统错误')
        }
      }
    },
    // TODO
    uploadCb({ data }) {
      console.log('data :>> ', data)
      switch (this.btnType) {
        case 1:
          this.invoiceList = [...this.invoiceList, ...data]
          break
        case 2:
          this.pickUpOrderList = [...this.pickUpOrderList, ...data]
          break
        case 3:
          this.deliveryGuideList = [...this.deliveryGuideList, ...data]
          break
        case 4:
          this.isfList = [...this.isfList, ...data]
          break

        default:
          this.invoicesPackingInfo = data
          break
      }
    },
    toUpload(i) {
      switch (i) {
        case 1:
          this.importInfo.title = '上传箱单发票'
          break
        case 2:
          this.importInfo.title = '上传提单'
          break
        case 3:
          this.importInfo.title = '上传派送指引'
          break
        case 4:
          this.importInfo.title = '上传ISF文件'
          break
        default:
          this.importInfo.title = '上传清关发票并解析数据'
          this.importInfo.staticFileName = 'hdClearanceInvoice'
          break
      }

      if (i === 5) {
        this.importInfo.actionUrl = this.actionUrl2
        this.importInfo.fileName = 'templateFile'
      } else {
        this.importInfo.actionUrl = this.actionUrl1
        this.importInfo.fileName = 'files'
      }
      this.btnType = i
      this.uploadDialog = true
    },
    onSubmit() {
      console.log('submit!')
    },

    submitForm() {
      let flag = false
      this.$refs.consolidatedOrderInfo.validate(valid => {
        if (valid) {
          console.log('submit')
          flag = true
        } else {
          console.log('error submit!!')
          flag = false
          return false
        }
      })
      if (!flag) {
        let tipStr = "清关+派送";
        if(this.type === 'expressDelivery') {
            tipStr = "快递派送";
        } else if(this.type === 'customsClearance') {
            tipStr = "清关";
        } else if(this.type === 'truckDelivery') {
            tipStr = "卡车派送";
        }

        this.$message.error({
          message:`请填写`+tipStr,
          offset:55,
          duration:1500
        })
        return
      }
      if (this.type === 'expressDelivery') {
        for (const i in this.goodsInfo) {
          for (const j in this.goodsRules) {
            if (!this.goodsInfo[i][j]) {
              this.$message.error(
                `请填写尺寸信息第${parseInt(i) + 1}行：${this.goodsRules[j]}`
              )
              return false
            }
          }
        }
      } else {
        if (this.$refs.sub.$refs.form) {
          this.$refs.sub.$refs.form.forEach(e => {
            e.validate(x => {
              if (!x) {
                flag = false
              }
            })
          })
        }
      }

      if (!flag) {
        this.$message.error('请填写运单信息')
        return
      }

      // TODO 判断上传文件 是否为空
      if (
        this.invoiceList.length === 0 &&
        (this.type === 'customsClearanceAndSend' ||
          this.type === 'customsClearance')
      ) {
        this.$message.error('请上传箱单发票')
        return
      }

      if (
        this.pickUpOrderList.length === 0 &&
        (this.type === 'customsClearanceAndSend' ||
          this.type === 'customsClearance')
      ) {
        this.$message.error('请上传提单')
        return
      }
      if (
        this.deliveryGuideList.length === 0 &&
        this.type !== 'expressDelivery' &&
        this.type !== 'customsClearance'
      ) {
        this.$message.error('请上传派送指引')
        return
      }
      if (
        this.isfList.length === 0 &&
        (this.type === 'customsClearanceAndSend' ||
          this.type === 'customsClearance') &&
        !this.isAir
      ) {
        this.$message.error('请上传ISP文件')
        return
      }
      // if (
      //   !this.invoicesPackingInfo &&
      //   (this.type === 'customsClearanceAndSend' ||
      //     this.type === 'customsClearance')
      // ) {
      //   this.$message.error('请上传箱单发票解析')
      //   return
      // }

      let HDform = clone(this.consolidatedOrderInfo)
      if (HDform.dispatchAddressCode) {
        const d = this.fbaCodeZipCodeMap[HDform.dispatchAddressCode]
        console.log('dispatchAddressCode :>> ', d)
        HDform.dispatcher = d.companyName
        HDform.dispatchLinkMan = d.contacts
        HDform.dispatchPhone = d.contactNumber
        HDform.dispatchProvince = d.province
        HDform.dispatchZipCode = d.zipCode
        HDform.dispatchCity = d.city
        HDform.dispatchAddress = d.address
      }
      let isExpress = false
      // 海空运
      HDform.type = this.createTpye === 'ToAirFreight' ? 1 : 0
      // palceOrderWay 下单方式
      if (this.type === 'expressDelivery') {
        HDform.palceOrderWay = 2
        // dimensions 尺寸表
        HDform.dimensions = this.goodsInfo
        isExpress = true
      } else {
        // waybillHdSubForms 分单
        const subList = clone(this.$refs.sub.subList)

        for (const i of subList) {
          if (i.dispatchAddressCode) {
            const d = this.fbaCodeZipCodeMap[i.dispatchAddressCode]
            console.log('dispatchAddressCode :>> ', d)
            i.dispatcher = d.companyName
            i.dispatchLinkMan = d.contacts
            i.dispatchPhone = d.contactNumber
            i.dispatchProvince = d.province
            i.dispatchZipCode = d.zipCode
            i.dispatchCity = d.city
            i.dispatchAddress = d.address
          }
        }

        HDform.waybillHdSubForms = subList

        // tmpAddAccessorys 末端箱单发票
        HDform.tmpAddAccessorys = this.invoiceList
        // ladingTmpAddAccessorys 提单
        HDform.ladingTmpAddAccessorys = this.pickUpOrderList
        // sendToGuideTmpAddAccessorys 派送指引
        HDform.sendToGuideTmpAddAccessorys = this.deliveryGuideList
        // sendISFAddAccessorys isf
        HDform.sendISFAddAccessorys = this.isfList
        // const a = clone(HDform)
        if (this.type === 'customsClearanceAndSend') {
          HDform.palceOrderWay = 0

          HDform = Object.assign(HDform, this.invoicesPackingInfo)
        } else if (this.type === 'customsClearance') {
          HDform.palceOrderWay = 1
          HDform = Object.assign(HDform, this.invoicesPackingInfo)
        } else {
          HDform.palceOrderWay = 3
        }
        HDform.delSubIds = this.$refs.sub.delSubIds
      }
      // this.saveExpress(HDform)
      this.saveWaybill(HDform, isExpress)
    },
    // 保存末端运单数据（清关+派送；0清关；1;快递派送2;卡车派送3）
    async saveWaybill(from, isExpress) {
      this.$store.dispatch('app/toggleDialog', true)
      let data = ''
      if (isExpress) {
        data = await saveExpressDispatch(from)
      } else {
        data = await saveWaybillHd(from)
      }
      if (data.code === 200) {
        this.$message({
          message: '提交成功！',
          type: 'success'
        })
        this.$router.push({ name: 'EndWaybillList' })
      } else {
        this.$message.error(data.message)
      }

      this.$store.dispatch('app/toggleDialog', false)
    },

    showImportDialog() {
      this.selectDispatch = true
    },
    dialogCb(params) {
      this.consolidatedOrderInfo = Object.assign(
        this.consolidatedOrderInfo,
        params
      )
    },
    onDel(type, i) {
      switch (type) {
        case 1:
          this.invoiceList.splice(i, 1)
          break
        case 2:
          this.pickUpOrderList.splice(i, 1)
          break
        case 3:
          this.deliveryGuideList.splice(i, 1)
          break
        case 4:
          this.isfList.splice(i, 1)
          break
      }
    },
    async saveShippingAddress() {
      for (const i in this.shippingRules) {
        if (!this.consolidatedOrderInfo[i]) {
          this.$message.error('请填写' + this.shippingRules[i] + '！')
          return
        }
      }
      this.$store.dispatch('app/toggleDialog', true)
      const data = await customerdeliveryaddressSave({
        id: '',
        customerDeliveryCompany: this.consolidatedOrderInfo.dispatcher,
        customerDeliveryAddressAttn: this.consolidatedOrderInfo.dispatchLinkMan,
        customerDeliveryAddressPhone: this.consolidatedOrderInfo.dispatchPhone,
        address: this.consolidatedOrderInfo.dispatchAddress,
        city: this.consolidatedOrderInfo.dispatchCity,
        state: this.consolidatedOrderInfo.dispatchProvince,
        countryId: this.consolidatedOrderInfo.countryId,
        zipCode: this.consolidatedOrderInfo.dispatchZipCode
      })
      if (data.code === 200) {
        this.$message({
          message: '保存成功！',
          type: 'success'
        })
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async changeCountry(val) {
      console.log('val :>> ', val)
      const { code, data, message } = await initShippingfbaStockBycountry({
        country: this.consolidatedOrderInfo.countryId
      })

      if (code !== 200) {
        this.$message.error(message)
        return
      }
      this.fbaCodeZipCodeMap = data
      console.log('data :>> ', data)
    }
  }
}
</script>

<style scoped>
.consolidatedOrderInformation >>> .el-select,
.el-date-editor.el-input {
  width: 100%;
}
.consolidatedOrderInformation >>> .el-card__body {
  padding: 0;
}
.consolidatedOrderInformation >>> .el-upload {
  text-align: left;
}
.text-right >>> .el-form-item__content {
  text-align: left;
}

@media screen and (min-width: 1200px) {
  .text-right >>> .el-form-item__label {
    text-align: right;
  }
}
</style>
